'use client'
import React, { useEffect, useCallback, useRef, useState } from 'react'
// import AMapLoader from '@amap/amap-jsapi-loader';

interface PointData {
    name: string;
    city: string;
    coordinate?: number[];
}

interface MapProps {
    width?: string;
    height?: string;
    zoom?: number;
    list: PointData[][]
    id?: string; // 添加可选的id属性
}

const Map: React.FC<MapProps> = ({ width = '100%', height = '300px', zoom = 13, list, id }) => {
    const mapRef = useRef<any>(null);
    const drivingInstancesRef = useRef<any[]>([]);
    const [loading, setLoading] = useState(true);
    // 生成唯一的容器ID
    const containerId = useRef<string>(id || `map-container-${Math.random().toString(36).substring(2, 9)}`);

    // 添加重试函数
    const retry = async (fn: Function, retries = 3, delay = 2000) => {
        try {
            return await fn();
        } catch (error) {
            if (retries === 0) throw error;
            await new Promise(resolve => setTimeout(resolve, delay));
            return retry(fn, retries - 1, delay);
        }
    };

    // 修改地址转换函数，添加重试机制
    const getCoordinate = useCallback(async (AMap: any, point: PointData) => {
        return retry(() => new Promise((resolve, reject) => {
            const geocoder = new AMap.Geocoder({
                city: "全国",
                batch: false
            });

            const address = `${point.city}${point.name}`;
            geocoder.getLocation(address, (status: string, result: any) => {
                if (status === 'complete' && result.info === 'OK' && result.geocodes?.[0]) {
                    resolve(result.geocodes[0].location);
                } else {
                    reject(new Error(`地址解析失败: ${address}`));
                }
            });
        }));
    }, []);



    // 渲染单条路线
    const renderSingleRoute = useCallback(async (AMap: any, map: any, path: PointData[], index: number) => {
        // 定义一组美观的颜色
        const colors = [
            '#1677ff', // 蓝色
            '#FF4500', // 橙色
            '#4ECDC4', // 绿松石  
            '#98FB98', // 淡绿色
            '#FFA07A', // 浅鲑鱼色
            '#00b7ff', // 天蓝色
            '#DDA0DD', // 梅红色
            '#F0E68C', // 卡其黄
            '#ff61a3',
            '#FF6B6B', // 珊瑚红
        ];

        try {
            console.log(`开始处理第${index + 1}条路线...`);
            // 获取所有点的坐标
            const coordinates = await Promise.all(
                path.map(point => getCoordinate(AMap, point))
            );

            console.log(`第${index + 1}条路线的坐标获取成功:`, coordinates);

            // 清理之前的路线实例
            if (drivingInstancesRef.current[index]) {
                try {
                    drivingInstancesRef.current[index].clear();
                    drivingInstancesRef.current[index].destroy();
                } catch (error) {
                    console.warn(`清理第${index + 1}条路线实例失败:`, error);
                }
            }

            // 创建新的driving实例
            let driving;
            try {
                driving = new AMap.Driving({
                    map: map,
                    hideMarkers: true,
                    showTraffic: true,
                    policy: AMap.DrivingPolicy.LEAST_TIME,
                    panel: false
                });

                if (!driving) {
                    throw new Error('Driving 实例创建失败');
                }

                drivingInstancesRef.current[index] = driving;
            } catch (error) {
                console.error(`创建第${index + 1}条路线的 Driving 实例失败:`, error);
                throw error;
            }

            // 添加所有点的标记
            coordinates.forEach((coord, idx) => {
                new AMap.Marker({
                    map: map,
                    position: coord,
                    label: {
                        content: path[idx].name,
                        direction: 'top'
                    }
                });
            });

            // 规划路线
            return new Promise((resolve, reject) => {
                const startPoint = coordinates[0];
                const endPoint = coordinates[coordinates.length - 1];
                const waypoints = coordinates.slice(1, -1);

                driving.search(
                    startPoint,
                    endPoint,
                    { waypoints },
                    (status: string, result: any) => {
                        if (status === 'complete') {
                            console.log(`第${index + 1}条路线规划成功`);
                            const routes = result.routes;
                            routes.forEach((route: any) => {
                                // 创建完整的路径数组
                                const pathArray: any[] = [];
                                route.steps.forEach((step: any) => {
                                    pathArray.push(...step.path);
                                });

                                // 使用完整的路径创建一条折线
                                new AMap.Polyline({
                                    map: map,
                                    path: pathArray,
                                    strokeColor: colors[index % colors.length],
                                    strokeWeight: 6,
                                    strokeOpacity: 0.8
                                });
                            });
                            resolve(result);
                        } else {
                            console.error(`第${index + 1}条路线规划失败：`, result);
                            reject(new Error(`路线${index + 1}规划失败`));
                        }
                    }
                );
            });
        } catch (error) {
            console.error(`第${index + 1}条路线处理失败：`, error);
            throw error;
        }
    }, [getCoordinate]);

    // 修改路线处理函数
    const processRoutes = useCallback(async (AMap: any, map: any, routes: PointData[][]) => {
        try {
            for (let i = 0; i < routes.length; i++) {
                await renderSingleRoute(AMap, map, routes[i], i);
                // 增加路线之间的延迟时间到 3 秒
                await new Promise(resolve => setTimeout(resolve, 3000));
            }
            map.setFitView();
        } catch (error) {
            console.error('路线处理失败：', error);
        } finally {
            setLoading(false);
        }
    }, [renderSingleRoute]);
    useEffect(() => {
        // 验证路线数据
        if (typeof window !== 'undefined') {
            if (!Array.isArray(list) || list.length === 0) {
                console.log('无效的路线数据');
                setLoading(false);
                return;
            }

            setLoading(true);

            // 设置安全密钥
            (window as any)._AMapSecurityConfig = {
                securityJsCode: '7708aad3ee4c3d13ea5ad0357666bce7'
            }

            // 初始化地图

            import('@amap/amap-jsapi-loader').then(AMapLoader => {
                AMapLoader.load({
                    key: '8782bc266f43ee30cc778a9c94613fd0',
                    version: '2.0',
                    plugins: ['AMap.Driving', 'AMap.Geocoder']
                })
            })
                .then(async (AMap: any) => {
                    try {
                        // 创建新的地图实例，使用唯一的容器ID
                        mapRef.current = new AMap.Map(containerId.current, {
                            zoom: zoom,
                            viewMode: '2D',
                            mapStyle: 'amap://styles/normal',
                            resizeEnable: true
                        });

                        // 处理所有路线
                        await processRoutes(AMap, mapRef.current, list);
                    } catch (error) {
                        console.error('地图初始化或路线处理失败：', error);
                        setLoading(false);
                    }
                }).catch(error => {
                    console.error('地图加载失败：', error);
                    setLoading(false);
                });
        }


        // 组件卸载时清理地图实例
        return () => {
            if (typeof window !== 'undefined') {
                if (mapRef.current) {
                    try {
                        // 清理所有路线实例
                        drivingInstancesRef.current.forEach(instance => {
                            if (instance) {
                                try {
                                    instance.clear();
                                    instance.destroy();
                                } catch (e) {
                                    console.warn('清理路线实例失败:', e);
                                }
                            }
                        });
                        // 销毁地图实例
                        mapRef.current.destroy();
                        mapRef.current = null;
                    } catch (e) {
                        console.warn('清理地图实例失败:', e);
                    }
                }
            }
        };
    }, [list, processRoutes, zoom]);

    return (
        <div style={{ position: 'relative', width, height }}>
            <div
                id={containerId.current}
                style={{
                    width: '100%',
                    height: '100%',
                    borderRadius: '10px',
                    overflow: 'hidden'
                }}
            />
            {loading && (
                <div style={{
                    position: 'absolute',
                    top: '50%',
                    left: '50%',
                    transform: 'translate(-50%, -50%)',
                    background: 'rgba(255, 255, 255, 0.8)',
                    padding: '10px 20px',
                    borderRadius: '4px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                }}>
                    正在加载路线...
                </div>
            )}
        </div>
    );
}

export default React.memo(Map);